#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

#include "../../../msgbus.h"

extern "C" {
static char *s_token = NULL;

void cb_handle(const char *topic, const char *data, int data_len, void *args)
{
    static int s_count = 0;
    if(true || s_count++ % 1000 == 0) {
        printf("[#%ld] c: #%d topic %s data %s data_len %d args %p\n", pthread_self(), s_count, topic, data, data_len, args);
        fflush(stdout);
    }
}

char* cb_call(const char *topic, const char *method, const char *data, int data_len, void *args, int *return_len)
{
    int size = data_len + 128;
    char * buff = (char*)malloc(size);
    memset(buff, 0, size);
    *return_len = snprintf(buff, size, "C %s call %s: ", topic, method);
    memcpy(buff + *return_len, data, data_len);
    *return_len = strlen(buff);
//    printf("call: %s\n", buff);
    return buff;
}

void start_subscribe(const char *topic) {
    MessageBusCallback  cb = {cb_handle, cb_call };
    s_token = subscribe(get_bus(), topic, cb, (void*)get_bus());
    printf("subscribe token %p %s\n", s_token, s_token);
}

void stop_subscribe() {
    if(s_token) {
        printf("unsubscribe token %s\n", s_token);
        unsubscribe(get_bus(), s_token);
        free(s_token);
        s_token = NULL;
    }
}
}
